function Pt = InvTalairach(P,M)
%inputs
% P : talairach coordinates
% M : coordinates of different anatomical points in patient frame
% previously asked to the user
% outputs 
% Pt : real patient coordinates
%P = [-33 -40 71.3]

% AC = [3.0	1.0	23.4];
% PC = [25.0	0.0	21.5];
% IHP = [-14.0	1.0	65.4];
% AP = [68.0	-5.9	32.2];
% PP = [-98.0	6.8	18.6];
% SP = [-19.0	6.8	88.9];
% IP = [-49.0	-20.5	-37.1];
% RP = [-19.0	-66.4	11.7];
% LP = [-16.0	64.5	11.7];
M=M';

x=P(1);
y=P(2);
P(1)=-y;
P(2)=x;
X = M(:,1);
Y = M(:,2);
M(:,1)=Y;
M(:,2)=-X;

AC = M(1,:);
PC = M(2,:);
IHP = M(3,:);
AP = M(4,:);
PP = M(5,:);
SP = M(6,:);
IP=  M(7,:);
RP = M(8,:);
LP = M(9,:);


%   Transformation from canonical MRI to AC PC
A = ((AC - IHP) * (PC - AC)') * (PC - AC);
IHProject = A / norm(PC - AC)^2 + IHP;

ex = (AC - PC);
ez = (IHProject - AC);
ey = cross(ex, ez);


ex = ex / norm(ex);
ey = ey / norm(ey);
ez = ez / norm(ez);
R = [ex' ey' ez']';

SP = AC + dot(SP-AC,ez)*ez;
IP = AC + dot(IP-AC,ez)*ez;
RP = AC + dot(RP-AC,ey)*ey;
LP = AC + dot(LP-AC,ey)*ey;
AP = AC + dot(AP-AC,ex)*ex;
PP = AC + dot(PP-AC,ex)*ex;

X1T = 79;
X2T = 23;
X3T = 70;
Y1T = 68;
Y2T = 68;
Z1T = 42;
Z2T = 74;%72

X1 = norm(PP - PC);
X2 = norm(AC - PC);
X3 = norm(AP - AC);

Y1 = norm(AC - RP);
Y2 = norm(LP - AC);

Z1 = norm(AC - IP);
Z2 = norm(SP - AC);


%   Transformation from Talairac to AC PC
if (P(1) < -X2T)
    Pt(1) = (X1 / X1T) * (P(1) + X2T) - X2;
end

if (P(1) < 0 && P(1) >= -X2T)
    Pt(1) = (X2 / X2T) * P(1);
end

if (P(1) >= 0)
    Pt(1) = (X3 / X3T) * P(1);
end

if (P(2) < 0)
    Pt(2) = (Y1 / Y1T) * P(2);
end

if (P(2) >= 0)
    Pt(2) = (Y2 / Y2T) * P(2);
end

if (P(3) < 0)
    Pt(3) = (Z1 / Z1T) * P(3);
end

if (P(3) >= 0)
    Pt(3) = (Z2 / Z2T) * P(3);
end
    
Pt = R \ (Pt)';
Pt = Pt' +  AC;
% x=Pt(1);
% y=Pt(2);
% Pt(1)=-y;
% Pt(2)=x;
%     